/**
 * 
 */
package me.myachievements.persistence.tag;

import java.util.Date;
import java.util.List;

import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;

import me.myachievements.persistence.PersistenceManagerImpl;
import me.myachievements.persistence.account.Account;
import me.myachievements.persistence.goal.Goal;

/**
 * @author besseym
 *
 */
public class TagPersistenceManagerImpl extends PersistenceManagerImpl<Tag>
		implements TagPersistenceManager {
	
	/**
	 * Constructor
	 */
	public TagPersistenceManagerImpl(){
		super(Tag.class);
	}
	
	/*
	 * (non-Javadoc)
	 * @see me.myachievements.persistence.PersistenceManagerImpl#update(me.myachievements.persistence.PersistentObject)
	 */
	@Override
	public void update(Tag tag){
		tag.setUpdatedOn(new Date());
		super.update(tag);
	}
	
	/*
	 * (non-Javadoc)
	 * @see me.myachievements.persistence.tag.TagPersistenceManager#get(java.lang.String)
	 */
	public Tag get(String value){
		return (Tag) this.getCurrentSession()
			.createCriteria(Tag.class)
			.add(Restrictions.eq("value", value))
			.uniqueResult();
	}
	
	/*
	 * (non-Javadoc)
	 * @see me.myachievements.persistence.tag.TagPersistenceManager#getAssociatedTags(java.lang.Long)
	 */
	public List<Tag> getAssociatedTags(Long goalId){
		
		return this.getCurrentSession()
			.createCriteria(Tag.class)
			.createAlias("goals", "g")
			.add(Restrictions.eq("g.id", goalId))
			.list();
	}
	
	/*
	 * (non-Javadoc)
	 * @see me.myachievements.persistence.tag.TagPersistenceManager#getNotAssociatedTags(java.lang.Long)
	 */
	public List<Tag> getNotAssociatedTags(Long goalId){
		
		String subQuery = "select tag.id from Tag as tag join tag.goals as goal with goal.id = :goal_id";
		String query = "from Tag as tag where tag.id not in (" + subQuery + ")";
		
		return this.getCurrentSession().createQuery(query).setLong("goal_id", goalId).list();
	}

}
